var log4js = require('log4js');
var logger = log4js.getLogger('DaifugoTable');
var table = require('../../../common/game/Table');
var util = require("util");
var Dfggame = require("../GameTable/Dfggame");
var nbPlayerRoom = 4;
var beginTime = 1;
var timeTour = 1; // Time waiting to finish tour
var cpuTime = {
    NormalSpeed: 1,
    FastSpeed: 0.2
};
var MessageTable = {
    DO_SMTH: "DO_SMTH",
    RE_SMTH: "RE_SMTH",
    DEAL_CARD: "DEAL_CARD",
    PASS_CARD: "PASS_CARD",
    FIND_ROOM: "find_table",
    ROOM_TALK: "ROOM_TALK",
    GET_NAME: "GET_NAME",
    GET_CARD: "GET_CARD",
    EXCHANGE_CARD: "EXCHANGE_CARD",
    GET_SOLUTION: "GET_SOLUTION",
    GET_RESULT: "GET_RESULT",
    SER_INFO: "USER_INFO",
    GAME_STATUS: "GAME_STATUS",
    LEVEL_CPU: "LEVEL_CPU",
    START_CARD_GAME: "START_CARD_GAME",
    DEAL_PROCESS: "DEAL_PROCESS",
    END_GAME: "END_GAME"
};
/*
 *
 *       Room master to room distribution, send message for socket's player
 *
 * */
var PlayerAction = {
    DealCard: 0,
    Pass: 1,
    GetCards: 2,
    Exchange: 4
};

function DaifugoTable(name, config) {
    this.mGameCard = new Dfggame.GameCard();
    logger.trace("enter constructor");
    logger.trace("exit constructor");
    table.Table.call(this, name, config);
}

// Inherit the prototype methods from Table object into DaifugoTable
util.inherits(DaifugoTable, table.Table);

module.exports = DaifugoTable;

DaifugoTable.Table = DaifugoTable;

DaifugoTable.prototype.init = function (cb) {
    logger.trace('enter init');
    var that = this;

    table.Table.init.call(this, function (result) {
        if (result === true) {
            that.on('data', DaifugoTable.processData);
        }
        cb(result);
    });
};

DaifugoTable.processData = function (data, that) {
    switch (data.action) {
        case 'init_table_game':
            break;
        case MessageTable.LEVEL_CPU :
            logger.info("Beginning add Player");
            for (var i = 0; i < that.players.length; i++) {
                if (that.players[i].type == "ai") {
                    that.mGameCard.addPlayer(0);
                }
            }
            that.mGameCard.addPlayer(1);
            that.dealer = that.players[0].name;
            //that.chTable.sendMessage({
            //    action: 'init_table_game',
            //    dealer: that.dealer
            //});
            this.mGameCard.init();
            for(var i=0; i<that.players.length; i++){
                that.players[i].chPlayer.sendMessage({
                        action: MessageTable.LEVEL_CPU,
                        levelCPU: data.levelCPU
                    }
                )
            }
            break;
        case MessageTable.GET_CARD :
            var cardsData = [];
            for (var i = 0; i < that.players.length; i++) {
                cardsData[i] = this.mGameCard.getMyCards(i);
            }
            that.chTable.sendMessage({
                action: MessageTable.GET_CARD,
                player: data.player,
                cardData: cardsData
            });
            break;
        case MessageTable.START_CARD_GAME :
            if (data.type == "user") {
                this.beginToPlay(that.mGameCard.currentTourGame.cPlayer.mIndex);
            }
            break;
        case MessageTable.DEAL_CARD :

            var iplayer = that.mGameCard.currentTourGame.cPlayer.mIndex;
            var checkPlayer = 4 - iplayer;

            if (data.player == checkPlayer) {
                that.chTable.sendMessage({
                    action: MessageTable.DEAL_PROCESS,
                    player: data.player,
                    removecard: data.dealcard
                });
                this.dealCardHuman(data.dealcard, function (solution) {
                    that.doAction(iplayer, PlayerAction.DealCard, solution);
                });
                if (data.type == "user") {
                    clearTimeout(this.timeoutx);
                }
            }
            break;
        case MessageTable.END_GAME :
            delete that.mGameCard;
    }
};

DaifugoTable.prototype.beginToPlay = function (iplayer) {
    var that = this;
    var gData = {};
    // gData = Game Data
    var iPlayer = 4 - iplayer;
    var time = cpuTime.NormalSpeed;
    if(this.mGameCard.mPlayers[3].status != PlayerStatus.Normal){
        time = cpuTime.FastSpeed;
    }
    gData.bLock = this.mGameCard.currentTourGame.bLock;
    gData.isEightFlush = this.mGameCard.currentTourGame.isEightFlush;
    gData.isLockingHand = this.mGameCard.isLockingHand;
    gData.lenCard = [];
    for(var i = 0; i< this.mGameCard.mPlayers.length; i++){
        gData.lenCard.push(this.mGameCard.mPlayers[i].lenCards);
    }
    that.chTable.sendMessage({
        action: MessageTable.GET_SOLUTION,
        player: iPlayer,
        tour: gData,
        timeToThink: time,
        cardsLock: this.mGameCard.currentTourGame.cardsLock

    });
    // Start to play this turn
    this.nextToPlay();
};

DaifugoTable.prototype.doAction = function (iplayer, action, data, callback) {
    var actionStatus = null;
    var that = this;
    switch (action) {
        case PlayerAction.DealCard:
            if (!this.mGameCard.verifyTurn(iplayer)) {
                return;
            }
            logger.info('Player ' + ' DEAL Card');
            actionStatus = this.mGameCard.playerDecideCards(data);
            if (data.length == 0) {
                action = PlayerAction.Pass;
            }
            break;
        case PlayerAction.GetCards:
            logger.info('Player ' + ' GET Card');
            var cardsData = this.mGameCard.getMyCards(iplayer);
            if (callback) {
                callback(cardsData);
            }
            break;
        case PlayerAction.Pass:
            if (this.mGameCard.verifyTurn(iplayer)) {
                return;
            }
            logger.info('Player ' + ' Pass');
            logger.info(data);
            actionStatus = this.mGameCard.playerDecideCards(data);
            break;
        case PlayerAction.Exchange:

            //
            // this.mGameCard.exchangeUserCard(data);
            //roomlogger.info(this.mGameRule.getMovingCards(this.mGameCard.getMyCards(1).myCards, 2, 1));
            logger.info(data);
            break;
    }

    if (actionStatus != null) {
        // Send all message
        for (var i = 0; i < this.mGameCard.mPlayers.length; i++) {
            if (this.mGameCard.mPlayers[i].mType == Dfggame.PlayerType.Human) {
                var myIndex = new Object();
                myIndex.idx = i;
                // ThinhND trick
                if (actionStatus.isTourFinish && that.mGameCard.mPlayers[iplayer].mType == Dfggame.PlayerType.Human && false) {
                    setTimeout(function () {
                        that.chTable.sendMessage({
                            action: MessageTable.GAME_STATUS,
                            me: iplayer == that.mGameCard.mPlayers[myIndex.idx].iplayer,
                            dealtype: action,
                            iplayer: iplayer,
                            data: data,
                            status: actionStatus,
                            toMe: (myIndex.idx - iplayer + that.mGameCard.mPlayers.length) % that.mGameCard.mPlayers.length
                        });
                    }, timeTour / 2 * 1000);
                }
                else {
                    that.chTable.sendMessage({
                        action: MessageTable.GAME_STATUS,
                        me: iplayer == that.mGameCard.mPlayers[myIndex.idx].iplayer,
                        dealtype: action,
                        iplayer: iplayer,
                        data: data,
                        status: actionStatus,
                        toMe: (myIndex.idx - iplayer + that.mGameCard.mPlayers.length) % that.mGameCard.mPlayers.length
                    });
                }
            }
        }

        // TODO: confirm to get all the action at here
        if (actionStatus.gameFinish != true) {
            if (actionStatus.isTourFinish && that.mGameCard.mPlayers[iplayer].mType == Dfggame.PlayerType.Human) {
                setTimeout(function () {
                    that.beginToPlay(actionStatus.nextPlayer);
                }, 2 * 1000);
            }
            else {
                that.beginToPlay(actionStatus.nextPlayer);
            }
        }
        else {
            logger.info("Ending game at room: " + this.id);
            var result = [];
            for (var i = 0; i < this.mGameCard.mPlayers.length; i++) {
                logger.info(this.mGameCard.mPlayers[i].mIndex + ": " + this.mGameCard.mPlayers[i].status);
                result.push({iplayer: i, rank: this.mGameCard.mPlayers[i].status});
            }

            // send game result
            for (var i = 0; i < this.mGameCard.mPlayers.length; i++) {
                if (this.mGameCard.mPlayers[i].mType == Dfggame.PlayerType.Human) {
                    that.chTable.sendMessage({
                        action: MessageTable.GET_RESULT,
                        result: result,
                        me: i
                    });
                }
            }
        }
    }
};
DaifugoTable.prototype.nextToPlay = function () {
    var that = this;
    var data = [];
    var iplayer = that.mGameCard.currentTourGame.cPlayer.mIndex;
    /* *
     * Delay 10 seconds for thinking
     * */
    if (this.mGameCard.mPlayers[iplayer].mType == Dfggame.PlayerType.Human) {
        that.timeoutx = setTimeout(function () {
            that.dealCardHuman([], function (solution) {
                that.doAction(iplayer, PlayerAction.DealCard, solution);
            })
        }, 10 * 1000);
    }
};
/*
 *
 * Processing deal card by user
 *
 * */
DaifugoTable.prototype.dealCardHuman = function (data, callback) {
    callback(data);
};